package com.chuanqi.admin.controller; 

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.chuanqi.admin.constants.Constants;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.chuanqi.admin.domain.Student;
import com.chuanqi.admin.dto.StudentJtableJsonResponse;
import com.chuanqi.admin.uploadconfig.PropertyPlaceholderConfig;
import com.chuanqi.common.utils.EncodeFilename;
import com.chuanqi.admin.qp.StudentQp;
import com.chuanqi.admin.service.StudentService;

import java.io.FileInputStream;
import java.util.Properties;

import org.springframework.context.annotation.Import;
import org.springframework.beans.factory.annotation.Value;

import java.util.UUID;

@Controller
@RequestMapping(value="/authc/student")
@Import(PropertyPlaceholderConfig.class)
public class StudentController {	
	private static final Logger logger = LogManager.getLogger(StudentController.class.getName());
		
	@Autowired
	private StudentService studentService;
	
	@Value("${file.upload.directory}")
    private String fileUploadDirectory;	
	
	@RequestMapping(value = "/miniupload", method = RequestMethod.GET)
    public String miniUploadGet(){		 
		String storageDirectory = fileUploadDirectory;
		System.out.println("storageDirectory=="+storageDirectory);
		
		return "authc/student/mini_upload_form";  
	}
	
	@RequestMapping(value = "/miniupload", method = RequestMethod.POST, produces="application/json")
    public @ResponseBody List<Map<String, Object>> miniUploadPost(MultipartHttpServletRequest request, HttpServletResponse response) {
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf;
        List<Map<String, Object>> mapList = Lists.newArrayList();
        
        while (itr.hasNext()) {
            mpf = request.getFile(itr.next());
            
            System.out.println("Uploading==="+mpf.getOriginalFilename());
            
            String newFilenameBase = UUID.randomUUID().toString();
            String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
            String newFilename = newFilenameBase + originalFileExtension;
            String storageDirectory = fileUploadDirectory.trim();
            String contentType = mpf.getContentType();
            
            //String pathname = 
            File newFile = new File(storageDirectory + "/" + newFilename);
            try {
                mpf.transferTo(newFile);
                
                Map<String, Object> map = Maps.newHashMap();
                map.put("newFilename", newFilename);
                map.put("contentType", contentType);
                
                mapList.add(map);
                
            } catch(IOException e) {                
                System.out.println("Could not upload file "+mpf.getOriginalFilename());
            }
            
        }
        
        return mapList;
    }		
	
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String uploadx(Model model, HttpServletRequest request) throws FileNotFoundException, IOException{		 
		String webPath = this.getClass().getClassLoader().getResource("/").getPath();
		System.out.println("webPath=="+webPath);
		
		String name = webPath + "fileUpload.properties";
		
		Properties properties = new Properties();
		FileInputStream in = new FileInputStream(name);
		properties.load(in);
		in.close();

		String username = properties.getProperty("username");
		String zip_code = properties.getProperty("zip_code");
		
		System.out.println("username=="+username);
		
		System.out.println("zip_code=="+zip_code);
		
		System.out.println("fileUploadDirectory=="+fileUploadDirectory);
		
		
		return "authc/student/upload";  
	}
	
	@RequestMapping(value="/create", method=RequestMethod.GET)
	public String createGet(Model model){
		Student student = new Student();
		model.addAttribute("student", student);
		model.addAttribute("action", "create");
		return "authc/student/form";
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createPost(@Valid @ModelAttribute("student") Student student, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
		if (bindingResult.hasErrors()) {
        	model.addAttribute("action", "create");        	
        	return "authc/student/form";
        }
        
		studentService.insert(student); 
        redirectAttributes.addFlashAttribute("message", Constants.create_sucess_message);
        return "redirect:/authc/student/list";
    }
	
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String updateGet(@PathVariable("id") Long id, Model model) {		
		Student student = studentService.getById(id);
		model.addAttribute("student", student);
		model.addAttribute("action", "update");
		return "authc/student/form";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("student") Student student, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
		if (result.hasErrors()) {
			model.addAttribute("action", "update");
			return "authc/student/form";
		}
		if (student != null) {
			studentService.update(student);
			redirectAttributes.addFlashAttribute("message", Constants.update_sucess_message);
		}
		
		return "redirect:/authc/student/list";
	}	
	
	@RequestMapping(value="/{id}/delete", method=RequestMethod.GET)
	public String deleteById(@PathVariable Long id, RedirectAttributes redirectAttributes){
		studentService.deleteById(id);
		redirectAttributes.addFlashAttribute("message", Constants.delete_sucess_message);
		return "redirect:/authc/student/list";
	}
	
	/*//@RequiresPermissions("student:view")
	@RequestMapping(value = "/list", method = RequestMethod.GET)	
	public String showFirstPageGet(Model model) {			
		final long rowCount = studentService.getTotalCount();			
		List<Student> students = studentService.getFirstPage();		
		int pageIndex = 1;
		int pageSize = 10;
		
		String sortName = "STDNTNAME";
		String sortOrder = "ASC";
	    
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
	    	model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);	
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", pageIndex);
		    model.addAttribute("to", pageSize);
		    
		    model.addAttribute("students", students);  
	    }     			
		 
		return "authc/student/list";  
	}
	
	//@RequiresPermissions("student:view")
	@RequestMapping(value = "/list", method = RequestMethod.POST)	
	public String queryPagePost(
			@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,    		  
    		HttpServletRequest request,
    		Model model) {			
		
		String sortName = request.getParameter("sortName"); 		
		String sortOrder = request.getParameter("sortOrder");	
				
		String stdntName = request.getParameter("stdntName");		
		String email = request.getParameter("email");
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "STDNTNAME";
			sortOrder = "ASC";
		}
		
		long offset = pageIndex > 0 ? (pageIndex - 1) * pageSize : 0;
		StudentQp qp = new StudentQp();
		qp.setOffset(offset);		
		qp.setPageSize(pageSize);
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);	
		qp.setStdntName(stdntName);	
		qp.setEmail(email);
		
		final long rowCount = studentService.getCountByQueryBean(qp);				
		List<Student> students = studentService.getByQueryBean(qp);			
		
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }    
	    
	    long from = (pageIndex - 1) * pageSize + 1;
		long to = 0l;
		
		if(pageIndex<totalPages){			
			to = pageIndex * pageSize;
		}else{
			to = rowCount;
		}			
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
			model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);			
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", from);
		    model.addAttribute("to", to);
		    
		    model.addAttribute("students", students);  
	    }     			
		 
	    return "authc/student/list";   
	}
	*/
	//jtable
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String showJtable(){ 
		return "authc/student/jtable";
	}
	
	//http://www.jtable.org/Demo/StudentList?jtStartIndex=0&jtPageSize=10&jtSorting=Name%20ASC
	@RequestMapping(value = "/studentList", method = RequestMethod.POST)	
	public @ResponseBody StudentJtableJsonResponse getJTableJson(HttpServletRequest request) {			
		
		System.out.println("getQueryString = " + request.getQueryString());
			
		long offset = Long.parseLong(request.getParameter("jtStartIndex"));
		int pageSize = Integer.parseInt(request.getParameter("jtPageSize")); 
		String jtSorting = request.getParameter("jtSorting");
		String[] jtSortingArray = jtSorting.split(" "); 		
		String sortName = jtSortingArray[0]; 		
		String sortOrder = jtSortingArray[1];		
				
		String stdntName = request.getParameter("stdntName");				
		String email = request.getParameter("email");   			
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "stdntName";
			sortOrder = "ASC";
		}		
		
		StudentQp qp = new StudentQp();		
		qp.setPageSize(pageSize);
		qp.setOffset(offset);
		qp.setStdntName(stdntName);
		qp.setEmail(email);	
		
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);		
		
		System.out.println("offset = " + offset);
		System.out.println("pageSize = " + pageSize);
					
		List<Student> records = studentService.getByQueryBean(qp);
		final long totalRecordCount = studentService.getCountByQueryBean(qp);
		
		System.out.println("totalRecordCount = " + totalRecordCount);		
		
		StudentJtableJsonResponse jtableJsonResponse = new StudentJtableJsonResponse();
		jtableJsonResponse.setResult("OK");
		jtableJsonResponse.setRecords(records);
		jtableJsonResponse.setTotalRecordCount(totalRecordCount);
		 
		return jtableJsonResponse;
	}		
	
	
	@RequestMapping(value="/import", method=RequestMethod.GET)
	public String importGet(){
		return "authc/student/import";
	}
	
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public String importPost(@RequestParam("file") MultipartFile file, Model model) throws IOException {		
		logger.info("....STARTTING import Excel....");
		String fileName = "";
		if (!file.isEmpty()) {
			fileName = file.getOriginalFilename();				
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());
			
			if ((".xlsx.xls".indexOf(suffix.toLowerCase()) != -1)) {
				Integer fileSize = (int) file.getSize() / 1024;
				
				if (fileSize <= 10240) {
					List<Student> stdntList = new ArrayList<Student>();
					//FileInputStream fis = (FileInputStream) file.getInputStream();
					HSSFWorkbook wb = new HSSFWorkbook(stream);
					HSSFSheet sheet = wb.getSheetAt(0);
					
					int rowNum = sheet.getLastRowNum()+1;
					for(int i=1; i<rowNum; i++){
						Student student = new Student();
						HSSFRow row = sheet.getRow(i);
						int cellNum = row.getLastCellNum();
						for(int j=0;j<cellNum;j++){
							HSSFCell cell = row.getCell(j);
							String cellValue = null;
							switch(cell.getCellType()){ 
								case 0 : cellValue = String.valueOf((int)cell.getNumericCellValue()); break;
								case 1 : cellValue = cell.getStringCellValue(); break;
								case 2 : cellValue = String.valueOf(cell.getDateCellValue()); break;
								case 3 : cellValue = ""; break;
								case 4 : cellValue = String.valueOf(cell.getBooleanCellValue()); break;
								case 5 : cellValue = String.valueOf(cell.getErrorCellValue()); break;
							}
							
							switch(j){
								//case 0 : student.setId(Long.valueOf(cellValue));break;
								case 0 : student.setStdntName(cellValue);break;
								case 1 : student.setEmail(cellValue);break;
							}
						}
						stdntList.add(student);
					}			
					
					for(Student s : stdntList){
						System.out.println(s.getStdntName());
					}
					fileName = fileName + "===" + stdntList.size();
					//--------------------------------------------------------
					int count = studentService.insertListBatch(stdntList);
					System.out.println("影响的行数："+count);
					//--------------------------------------------------------
				} else {
					System.out.println("上传的文件太大，文件大小不能超过10M");
					
				}
				
			} else {
				System.out.println("上传的文件格式不支持");	
				logger.error("....文件格式不支持,不是EXCEL格式啊....");
			}		
			
		}			
		
		model.addAttribute("fileName", fileName);
		
		logger.info("....finishing import excel over....");
		
		return "authc/student/uploadSuccess";
	}	
	
	/**
	 * Handle request to download an Excel document 
	 * @throws IOException 
	 */
	@RequestMapping(value = "/export", method = RequestMethod.POST)	
	public void exportGet(HttpServletRequest request, HttpServletResponse response) throws IOException  {		
		String sortName = request.getParameter("sortName"); 		
		String sortOrder = request.getParameter("sortOrder");
		
		String stdntName = request.getParameter("stdntName");		
		String email = request.getParameter("email");
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "STDNTNAME";
			sortOrder = "ASC";
		}		
		
		StudentQp qp = new StudentQp();		
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);	
		qp.setStdntName(stdntName);	
		qp.setEmail(email);
					
		// create data
		List<Student> list = studentService.getList(qp);		
				
		for(Student c : list){
			System.out.println(c.getStdntName());
		}
		
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		String month_ = new String("" + month);
		if (month < 10) {
			month_ = "0" + month;
		}
		int day = c.get(Calendar.DAY_OF_MONTH);
		String day_ = new String("" + day);
		if (day < 10) {
			day_ = "0" + day;
		}

		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);

		StringBuilder fileName = new StringBuilder();
		fileName.append("客户列表").append("-");
		fileName.append(year).append(month_).append(day_);
		fileName.append("-");
		fileName.append(hour).append(minute).append(second);		
		fileName.append(".xls");
		
		String filename = EncodeFilename.encodeFileName(request, fileName.toString());  
		
        // create a new workbook
		HSSFWorkbook workbook = new HSSFWorkbook();

		// create a new Excel sheet
		HSSFSheet sheet = workbook.createSheet();
		sheet.setDefaultColumnWidth(30);
		
		// create style for header cells
		CellStyle style = workbook.createCellStyle();
		Font font = workbook.createFont();
		font.setFontName("Arial");
		style.setFillForegroundColor(HSSFColor.BLUE.index);
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setColor(HSSFColor.WHITE.index);
		style.setFont(font);
		
		// create header row
		HSSFRow header = sheet.createRow(0);
		
		header.createCell(0).setCellValue("stdntName");
		header.getCell(0).setCellStyle(style);
		
		header.createCell(1).setCellValue("email");
		header.getCell(1).setCellStyle(style);
		
		// create data rows
		int rowCount = 1;
		
		for (Student student : list) {
			HSSFRow aRow = sheet.createRow(rowCount++);			
			aRow.createCell(0).setCellValue(student.getStdntName());
			aRow.createCell(1).setCellValue(student.getEmail());			
		}
		
		// write the workbook to the output stream
		// close our file (don't blow out our file handles
		response.setContentType("application/vnd.ms-excel");     
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
		ServletOutputStream ouputStream = response.getOutputStream();  
		workbook.write(ouputStream);  
        ouputStream.flush();  
        ouputStream.close();  			
	}		
	
	//@RequiresPermissions("student:view")
	@RequestMapping(value="/get", method=RequestMethod.GET)
	public String getStudent(HttpServletRequest request, Model model){
		logger.info("开始获取数据.......");
		Student student = studentService.getById(240L);		
		model.addAttribute("student", student);  		
		logger.info("获取数据结束......");
		return "student/index";
	}		
	
	//@RequiresPermissions("student:view")
	@RequestMapping(value="/{id}",method=RequestMethod.GET)
	public String getStudentById(@PathVariable long id, Model model){
		logger.info("student id: " + id);
		logger.info("开始获取数据.......");
		Student student = studentService.getById(id);		
		model.addAttribute("student", student);  		
		logger.info("获取数据结束......");
		return "student/index";
	}
	
	//@RequiresPermissions("student:view")
	@RequestMapping(value="/getAll", method=RequestMethod.GET)
	public String getAllStudents(HttpServletRequest request, Model model){
		logger.info("开始获取数据.......");
		List<Student> allStudents = studentService.getAll();		
		model.addAttribute("allStudents", allStudents);  		
		logger.info("获取数据结束......");
		return "student/allStudents";
	}
	
}
